import { Injectable, Logger } from "@nestjs/common";
import { InjectRepository } from "@nestjs/typeorm";
import { Repository, DataSource } from "typeorm";
import { CharacterEquipmentInventoryEntity } from "../entities/character-equipment-inventory.entity";
import { EquipmentBaseEntity } from "../entities/equipment-base.entity";
import { CharacterEntity } from "../entities/character.entity";
import { EquipmentGemSocketEntity } from "../entities/equipment-gem-socket.entity";

@Injectable()
export class CharacterEquipmentInventoryService {
  private readonly logger = new Logger(CharacterEquipmentInventoryService.name);

  constructor(
    @InjectRepository(CharacterEquipmentInventoryEntity)
    private readonly equipmentInventoryRepository: Repository<CharacterEquipmentInventoryEntity>,
    @InjectRepository(EquipmentBaseEntity)
    private readonly equipmentBaseRepository: Repository<EquipmentBaseEntity>,
    @InjectRepository(CharacterEntity)
    private readonly characterRepository: Repository<CharacterEntity>,
    private readonly dataSource: DataSource
  ) {}

  /**
   * 添加装备到装备背包表
   */
  async addEquipmentToInventory(
    characterId: number,
    equipmentId: number,
    count: number = 1
  ): Promise<{ success: boolean; message: string }> {
    const queryRunner = this.dataSource.createQueryRunner();
    await queryRunner.connect();
    await queryRunner.startTransaction();

    try {
      // 获取装备信息
      const equipment = await queryRunner.manager.findOne(EquipmentBaseEntity, {
        where: { id: equipmentId },
      });

      if (!equipment) {
        throw new Error("装备不存在");
      }

      // 检查角色是否存在
      const character = await queryRunner.manager.findOne(CharacterEntity, {
        where: { id: characterId },
      });

      if (!character) {
        throw new Error("角色不存在");
      }

      // 检查装备背包表中是否已存在此装备
      const existingEquipment = await queryRunner.manager.findOne(
        CharacterEquipmentInventoryEntity,
        {
          where: { characterId, equipmentId, status: 1 },
        }
      );

      if (existingEquipment) {
        // 如果已存在，进行数量叠加
        await queryRunner.manager.update(
          CharacterEquipmentInventoryEntity,
          { id: existingEquipment.id },
          {
            num: existingEquipment.num + count,
            updated_at: new Date(),
          }
        );
      } else {
        // 如果不存在，创建新记录
        await queryRunner.manager.insert(CharacterEquipmentInventoryEntity, {
          characterId,
          equipmentId: equipment.id,
          name: equipment.name,
          itemType: 2, // 装备类型
          num: count,
          status: 1,
          pic: equipment.image,
          description: equipment.intro,
          level: equipment.level,
          weight: equipment.weight,
          price: equipment.price,
          intro: equipment.intro,
          reqLevel: equipment.req_level || 0,
          reqStrength: equipment.req_strength || 0,
          reqConstitution: equipment.req_constitution || 0,
          reqAgility: equipment.req_agility || 0,
          reqIntelligence: equipment.req_intelligence || 0,
          bonusAttack: equipment.bonus_attack || 0,
          bonusHp: equipment.bonus_hp || 0,
          bonusMp: equipment.bonus_mp || 0,
          bonusDefense: equipment.bonus_defense || 0,
          resistanceType: equipment.resistance_type || "",
          resistanceValue: equipment.resistance_value || 0,
          rarity: 1, // 默认稀有度
          obtainedAt: new Date(),
          created_at: new Date(),
          updated_at: new Date(),
        });
      }

      await queryRunner.commitTransaction();

      this.logger.log(
        `装备添加成功: ${equipment.name} x${count} (角色ID: ${characterId})`
      );
      return {
        success: true,
        message: `成功添加 ${count} 个${equipment.name}到装备背包`,
      };
    } catch (error) {
      await queryRunner.rollbackTransaction();
      this.logger.error(`添加装备失败:`, error);
      throw error;
    } finally {
      await queryRunner.release();
    }
  }

  /**
   * 查询角色装备信息
   */
  async getCharacterEquipment(
    characterId: number,
    pageNum: number = 0,
    pageSize: number = 20
  ) {
    try {
      const [equipments, total] =
        await this.equipmentInventoryRepository.findAndCount({
          where: {
            characterId,
            itemType: 2, // 装备类型
            status: 1, // 正常状态
          },
          skip: pageNum * pageSize,
          take: pageSize,
          order: { obtainedAt: "DESC" },
          relations: ["equipmentBase"],
        });

      // 按照标准格式返回数据
      const list = equipments.map((equipment: any) => ({
        id: equipment.equipmentId, // 使用装备ID而不是装备背包表ID
        name: equipment.name || equipment.equipmentBase?.name || "",
        num: equipment.num,
        type: equipment.itemType,
        level: equipment.level,
        weight: equipment.weight,
        price: equipment.price,
        intro: equipment.intro,
        reqLevel: equipment.reqLevel,
        bonusAttack: equipment.bonusAttack,
        bonusHp: equipment.bonusHp,
        bonusMp: equipment.bonusMp,
        bonusDefense: equipment.bonusDefense,
      }));

      return {
        list,
        total,
        page: pageNum + 1,
        sum: total,
      };
    } catch (error) {
      console.error("查询角色装备失败:", error);
      throw error;
    }
  }

  /**
   * 丢弃装备（按数量）
   */
  async discardEquipment(
    characterId: number,
    equipmentId: number
  ): Promise<{ success: boolean; message: string }> {
    const queryRunner = this.dataSource.createQueryRunner();
    await queryRunner.connect();
    await queryRunner.startTransaction();

    try {
      // 查找装备背包表中的装备
      const equipment = await queryRunner.manager.findOne(
        CharacterEquipmentInventoryEntity,
        {
          where: {
            characterId,
            id: equipmentId, // 使用装备背包表的ID，不是装备基础表的ID
            status: 1, // 只查找正常状态的装备
          },
        }
      );

      if (!equipment) {
        await queryRunner.rollbackTransaction();
        return {
          success: false,
          message: "装备不存在或已被丢弃",
        };
      }

      // 删除装备宝石镶嵌表的数据
      await queryRunner.manager.delete(EquipmentGemSocketEntity, {
        characterId,
        equipmentId: equipment.id, // 使用装备背包表的ID
      });

      // 删除装备背包表中的装备记录
      await queryRunner.manager.delete(CharacterEquipmentInventoryEntity, {
        id: equipment.id,
      });

      await queryRunner.commitTransaction();

      return {
        success: true,
        message: `成功丢弃装备：${equipment.name}`,
      };
    } catch (error) {
      await queryRunner.rollbackTransaction();
      console.error("丢弃装备失败:", error);
      throw error;
    } finally {
      await queryRunner.release();
    }
  }

  /**
   * 使用装备
   */
  async useEquipment(
    characterId: number,
    equipmentId: number,
    count: number = 1
  ): Promise<{ success: boolean; message: string; remainingCount?: number }> {
    try {
      // 查找装备背包表中的装备
      const equipment = await this.equipmentInventoryRepository.findOne({
        where: {
          characterId,
          equipmentId,
          status: 1, // 只查找正常状态的装备
        },
      });

      if (!equipment) {
        return {
          success: false,
          message: "装备背包表中没有该装备",
        };
      }

      if (equipment.num < count) {
        return {
          success: false,
          message: `装备背包表中该装备数量不足，当前数量：${equipment.num}`,
        };
      }

      const remainingCount = equipment.num - count;

      if (remainingCount <= 0) {
        // 如果使用后数量为0或负数，直接删除该装备记录
        await this.equipmentInventoryRepository.update(equipment.id, {
          status: 0, // 标记为已使用
          updated_at: new Date(),
        });
        return {
          success: true,
          message: `成功使用 ${count} 个${equipment.name}`,
          remainingCount: 0,
        };
      } else {
        // 如果还有剩余，更新数量
        await this.equipmentInventoryRepository.update(equipment.id, {
          num: remainingCount,
          updated_at: new Date(),
        });
        return {
          success: true,
          message: `成功使用 ${count} 个${equipment.name}，剩余 ${remainingCount} 个`,
          remainingCount,
        };
      }
    } catch (error) {
      console.error("使用装备失败:", error);
      throw error;
    }
  }

  /**
   * 根据ID获取装备信息
   */
  async getEquipmentById(
    characterId: number,
    equipmentId: number
  ): Promise<any> {
    try {
      // 允许查询已穿戴(status=0)与未穿戴(status=1)的装备
      const equipment = await this.equipmentInventoryRepository.findOne({
        where: {
          id: equipmentId,
          characterId: characterId,
        },
        relations: ["equipmentBase"],
      });

      return equipment;
    } catch (error) {
      console.error("获取装备信息失败:", error);
      throw error;
    }
  }

  /**
   * 按装备基础类型查询角色可佩戴的装备（包含已装备与未装备）
   * @param characterId 角色ID
   * @param baseType 装备基础类型（1 头，2 右手，3 身体，4 项链，5 左手，6 脚）
   * @param pageNum 页码（从0开始）
   * @param pageSize 每页数量
   */
  async getEquipmentsByBaseType(
    characterId: number,
    baseType: number,
    pageNum: number = 0,
    pageSize: number = 20
  ): Promise<{ list: any[]; total: number }> {
    // 说明：这里包含 status 为 0(已装备) 与 1(背包中) 的记录
    // 通过关联 equipmentBase 并按 base.type 过滤
    try {
      const qb = this.equipmentInventoryRepository
        .createQueryBuilder("inv")
        .leftJoinAndSelect("inv.equipmentBase", "base")
        .where("inv.characterId = :characterId", { characterId })
        .andWhere("inv.status IN (:...statuses)", { statuses: [0, 1] })
        .andWhere("base.type = :baseType", { baseType })
        .orderBy("inv.level", "DESC")
        .skip(pageNum * pageSize)
        .take(pageSize);

      const [items, total] = await qb.getManyAndCount();

      const list = items.map((equipment: any) => ({
        id: equipment.id, // 背包记录ID（用于装备/卸下等）
        level: equipment.level,
        name: equipment.name || equipment.equipmentBase?.name || "",
        status: equipment.status,
        equipmentBase: equipment.equipmentBase,
      }));

      return { list, total };
    } catch (error) {
      console.error("按基础类型查询装备失败:", error);
      throw error;
    }
  }
}
